package bind

import (
	"encoding/json"
	"fmt"
	"peilian-api/app/global/errors"
	"peilian-api/app/global/log"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator"
)

func ShouldBinding(ctx *gin.Context, obj interface{}) error {
	method := strings.ToUpper(ctx.Request.Method)
	var err error = nil
	if method == "GET" {
		err = ctx.ShouldBindQuery(obj)
	} else if method == "POST" {
		err = ctx.ShouldBindJSON(obj)
	} else if method == "DELETE" {
		err = ctx.ShouldBindUri(obj)
	} else if method == "PUT" {
		err = ctx.ShouldBindJSON(obj)
	}
	err1 := ctx.ShouldBindUri(obj)
	if err1 != nil || err != nil {
		str, _ := json.Marshal(obj)
		log.Logger.ErrorF(ctx, fmt.Sprintf("传入参数: %v", str))
		return fmt.Errorf(errors.ParamBindError)
	}
	if err := validator.New().Struct(obj); err != nil {
		log.Logger.ErrorF(ctx, fmt.Sprintf("参数校验error: %v", err.Error()))
		fmt.Println(err.Error())
		return fmt.Errorf(errors.ParamValidateError)
	}

	str, _ := json.Marshal(obj)
	log.Logger.InfoF(ctx, fmt.Sprintf("传入参数: %s", string(str)))

	// t := reflect.TypeOf(obj)
	// v := reflect.ValueOf(obj)
	// if v.Elem().Kind() == reflect.Struct {
	// 	strMap := make(map[string]interface{})
	// 	for i := 0; i < v.Elem().NumField(); i++ {
	// 		strMap[t.Elem().Field(i).Name] = v.Elem().Field(i).String()
	// 	}
	// 	fmt.Println(strMap)
	// 	str, _ := json.Marshal(obj)
	// 	fmt.Println(string(str))
	// 	log.Logger.InfoF(ctx, fmt.Sprintf("传入参数: %v", strMap))
	// 	return nil
	// }
	return nil
}
